package com.xci.sys.api;

import cn.hutool.crypto.SecureUtil;
import com.xci.core.base.ApiController;
import com.xci.core.base.RestMessage;
import com.xci.core.domain.UpgradeModel;
import com.xci.core.domain.UploadInfo;
import com.xci.core.helper.Helper;
import com.xci.core.helper.JsonHelper;
import com.xci.core.helper.WebHelper;
import com.xci.core.internal.Const;
import com.xci.core.internal.Sys;
import com.xci.core.setting.UploadSetting;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 更新包接口
 *
 * @author 吕艳阳
 */
@ApiSort(17)
@Api(tags = "更新包接口")
@RestController
@RequestMapping(value = "/api/sys/upgrade", produces = Const.P_JSON)
public class UpgradeApiController extends ApiController {
    @Resource
    private UploadSetting uploadSetting;

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "检测更新")
    @ApiImplicitParam(name = "version", value = "当前版本号", required = true)
    @PostMapping("/update")
    public RestMessage<List<UpgradeModel>> update(@NotNull(message = "请指定当前版本号") @RequestParam Integer version) {
        //String appId = ApiHelper.currentApp().getId();
        List<UpgradeModel> data = loadPackageInfo();
        List<UpgradeModel> newData = data.stream().filter(p -> p.getVersion() > version).collect(Collectors.toList());
        setDataUrl(newData);
        return RestMessage.success(newData);
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "上传更新包")
    @PostMapping("/add")
    public RestMessage add(MultipartFile uFile, @RequestParam(required = false) String password) {
        if(Helper.isBlank(password) || !SecureUtil.md5(uploadSetting.getUpgradePassword()).equals(password)){
            return RestMessage.fail("您没有上传权限");
        }
        // String appId = ApiHelper.currentApp().getId();
        String name = Helper.nextId() + ".zip";
        // var setting = new UploadSetting();
        // setting.setAllowExtension(new String[]{"zip"});
        // setting.setAllowMaxSize(1024 * 500);//最大500M
        String path = "/upgrade/" + name;

        RestMessage<UploadInfo> result = Sys.me().uploadFile(uFile, path);
        if (result.isSuccess()) {
            List<UpgradeModel> data = loadPackageInfo();
            UpgradeModel upgradeModel = new UpgradeModel();
            upgradeModel.setVersion(1);
            data.stream().max(Comparator.comparingInt(UpgradeModel::getVersion)).ifPresent(p -> upgradeModel.setVersion(p.getVersion() + 1));
            upgradeModel.setName(name);
            upgradeModel.setCreateTime(new Date());
            data.add(upgradeModel);
            JsonHelper.saveList(getPackagePath(), data);
        }
        return result;
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "查询更新记录")
    @PostMapping("/list")
    public RestMessage<List<UpgradeModel>> list(HttpServletRequest request) {
        //String appId = ApiHelper.currentApp().getId();
        List<UpgradeModel> data = loadPackageInfo();
        setDataUrl(data);
        return RestMessage.success(data);
    }

    private String getPackagePath() {
        return Sys.buildPath("/upgrade/upgrades.json");
    }

    private List<UpgradeModel> loadPackageInfo() {
        return JsonHelper.loadList(getPackagePath(), ArrayList.class, UpgradeModel.class);
    }

    private void setDataUrl(List<UpgradeModel> data) {
        for (UpgradeModel info : data) {
            info.setUrl(WebHelper.getSiteFullUrl("/upgrade/" + info.getName()));
        }
    }
}